package com.zeny.coding.controller.admin.business;


import com.zeny.coding.constants.CourseConstants;
import com.zeny.coding.dto.CategoryDto;
import com.zeny.coding.dto.Response;
import com.zeny.coding.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.xml.bind.ValidationException;
import java.util.List;

/**
 * <h2>分类</h2>
 *
 * @Author Zeny
 */
@SuppressWarnings("all")
@RestController
@RequestMapping("/business/admin/category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping("/list")
    public Response list(@RequestParam(value = "parent",defaultValue = "00000000") String parent){
        List<CategoryDto> list= categoryService.list(parent);
        return new Response().success().data(list).message(CourseConstants.QUERY_SUCCESS);
    }

    @PostMapping("/save")
    public Response save(@RequestBody CategoryDto categoryDto) throws ValidationException {
        categoryDto.isValidForSave();
        this.categoryService.save(categoryDto);
        return new Response().success().message(CourseConstants.SAVE_SUCCESS);
    }

    @PutMapping("/update")
    public Response update(@RequestBody CategoryDto categoryDto) throws ValidationException {
        categoryDto.isValidForUpdate();
        this.categoryService.update(categoryDto);
        return new Response().success().message(CourseConstants.UPDATE_SUCCESS);
    }

    @GetMapping("/findById/{id}")
    public Response findById(@PathVariable("id") String id) {
        if (StringUtils.isEmpty(id)) {
            return new Response().fail().message(CourseConstants.REQUEST_PARAMS_ERROR);
        }
        CategoryDto categoryDto = this.categoryService.findById(id);
        return new Response()
                .success()
                .data(categoryDto)
                .message(CourseConstants.QUERY_SUCCESS);
    }

    @DeleteMapping("/deleteById/{id}")
    public Response deleteById(@PathVariable("id") String id) {
        if (StringUtils.isEmpty(id)) {
            return new Response().fail().message(CourseConstants.REQUEST_PARAMS_ERROR);
        }
        this.categoryService.deleteById(id);
        return new Response().success().message(CourseConstants.DELETE_SUCCESS);
    }

    @PostMapping("/all")
    public Response all() {
        List<CategoryDto> categoryDtoList = this.categoryService.findAll();
        return new Response().success().data(categoryDtoList).message(CourseConstants.QUERY_SUCCESS);
    }
}
